using AvalonAdmin.BaseViewModel;
using AvalonAdmin.Helpers;
using AvalonAdmin.Models;
using AvalonAdmin.Pages.CarParts.Views;
using AvalonAdmin.Pages.CarType.Views.Brand;
using AvalonAdmin.Pages.CarType.Views.CarTypeVersion;
using AvalonAdmin.Pages.CarType.Views.VehicleSeries;
using AvalonAdminDto.Common;

using AvalonAdminDto.Rule.RuleMappingDtos;
using AvalonAdminDto.CarType.VehicleSeriesDtos;
using AvalonAdminDto.CarType.CarTypeDtos;
using AvalonAdminDto.CarType.CarTypeVersionDtos;
using AvalonAdminDto.CarParts.CarPartsDtos;
using AvalonAdminDto.CarType.BrandDtos;
using D.UtilCore.Dtos;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Ursa.Controls;

namespace AvalonAdmin.Pages.Rule.ViewModels.RuleMapping
{
    /// <summary>
    /// 规则映射修改视图模型
    /// </summary>
    public class RuleMappingModifyViewModel : BaseModifyViewModel
    {
        #region 构造函数

        private readonly string? _ruleId;

        public RuleMappingModifyViewModel(string? id = null, string? ruleId = null, ViewStatus? viewStatus = null)
        {
            _ruleId = ruleId;
            Id = id;
            ViewStatus = viewStatus ?? ViewStatus.Add;
            LoadData();
        }

        #endregion

        #region 属性

        private string? _key;
        /// <summary>
        /// 映射键
        /// </summary>
        [Required(ErrorMessage = "映射键不能为空")]
        public string? Key
        {
            get => _key;
            set => SetProperty(ref _key, value);
        }

        private string? _val;
        /// <summary>
        /// 映射值
        /// </summary>
        [Required(ErrorMessage = "映射值不能为空")]
        public string? Val
        {
            get => _val;
            set => SetProperty(ref _val, value);
        }

        private string? _regStr;
        /// <summary>
        /// 正则表达式
        /// </summary>
        public string? RegStr
        {
            get => _regStr;
            set => SetProperty(ref _regStr, value);
        }

        private string? _description;
        /// <summary>
        /// 描述
        /// </summary>
        public string? Description
        {
            get => _description;
            set => SetProperty(ref _description, value);
        }

        private ObservableCollection<string> _mappingDetailsDisplayTypeList = new();
        /// <summary>
        /// 映射详情显示类型列表
        /// </summary>
        public ObservableCollection<string> MappingDetailsDisplayTypeList
        {
            get => _mappingDetailsDisplayTypeList;
            set => SetProperty(ref _mappingDetailsDisplayTypeList, value);
        }

        private ObservableCollection<MappingDetails> _mappingDetailsList = new();
        /// <summary>
        /// 映射详情列表
        /// </summary>
        public ObservableCollection<MappingDetails> MappingDetailsList
        {
            get => _mappingDetailsList;
            set => SetProperty(ref _mappingDetailsList, value);
        }

        private int _selectedTypeIndex;
        /// <summary>
        /// 选中的类型索引
        /// </summary>
        public int SelectedTypeIndex
        {
            get => _selectedTypeIndex;
            set => SetProperty(ref _selectedTypeIndex, value);
        }

        #endregion

        #region 数据加载

        /// <summary>
        /// 加载数据
        /// </summary>
        protected async Task LoadData()
        {
            try
            {
                // 初始化映射详情显示类型列表
                string[] values = Enum.GetNames(typeof(MappingDetailsDisplayType));
                MappingDetailsDisplayTypeList.Clear();
                foreach (var value in values)
                {
                    MappingDetailsDisplayTypeList.Add(value);
                }
                
                if (!string.IsNullOrEmpty(Id))
                {
                    await ExecuteWithLoadingAsync(async () =>
                    {
                        var res = await HttpHelper<RepRuleMapping>.GetAsync($"{ApiUrl.GetRuleMapping}/{Id}");

                        if (res.Code == StatusCodeEnum.OK && res.Data != null)
                        {
                            Key = res.Data.Key;
                            Description = res.Data.Descption;
                            Val = res.Data.Val;
                            RegStr = res.Data.RegStr;
                            SelectedTypeIndex = (int)res.Data.Details.Type;
                            SelectedTypeChange(SelectedTypeIndex);

                            MappingDetailsList.Clear();
                            if (res.Data.Details.ValueDetailsList != null)
                            {
                                foreach (var item in res.Data.Details.ValueDetailsList)
                                {
                                    MappingDetailsList.Add(new MappingDetails
                                    {
                                        Key = item.Key,
                                        Value = item.Value
                                    });
                                }
                            }
                            else if (res.Data.Details.ReferenceDetails != null)
                            {
                                MappingDetailsList.Add(new MappingDetails
                                {
                                    Key = res.Data.Details.ReferenceDetails.Key,
                                    Value = res.Data.Details.ReferenceDetails.Value,
                                    Id = res.Data.Details.ReferenceDetails.Id
                                });
                            }
                        }
                        else
                        {
                            await MessageBox.ShowAsync("加载数据失败: " + res.Msg);
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                await MessageBox.ShowAsync("加载数据异常: " + ex.Message);
            }
        }

        #endregion

        /// <summary>
        /// 选中类型变更处理
        /// </summary>
        /// <param name="index">类型索引</param>
        private void SelectedTypeChange(int index)
        {
            // 根据选中的类型索引处理相应逻辑
            // 这里可以添加具体的业务逻辑
        }

        #region CRUD操作

        /// <summary>
        /// 保存数据
        /// </summary>
        public async Task SaveAsync()
        {
            if (!ValidateInput())
                return;

            await ExecuteWithLoadingAsync(async () =>
            {
                var ruleMapping = new RepRuleMapping
                {
                    Id = Id,
                    Key = Key,
                    Val = Val,
                    RegStr = RegStr,
                    Descption = Description,
                    RuleId = _ruleId
                };

                ApiResult result;
                if (ViewStatus == ViewStatus.Add)
                {
                    result = await HttpHelper<RepRuleMapping>.PostAsync(ApiUrl.AddRuleMapping, ruleMapping);
                }
                else
                {
                    result = await HttpHelper<RepRuleMapping>.PutAsync(ApiUrl.UpdateRuleMapping, ruleMapping);
                }

                if (result.Code == StatusCodeEnum.OK)
                {
                    await MessageBox.ShowAsync(ViewStatus == ViewStatus.Add ? "添加成功" : "更新成功");
                    OnSaveCompleted();
                }
                else
                {
                    await MessageBox.ShowAsync($"操作失败: {result.Msg}");
                }
            });
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        public async Task DeleteAsync()
        {
            if (string.IsNullOrEmpty(Id))
                return;

            var result = await MessageBox.ShowAsync("确定要删除这条规则映射吗？", "确认删除", MessageBoxButton.YesNo);
            if (result != MessageBoxResult.Yes)
                return;

            await ExecuteWithLoadingAsync(async () =>
            {
                var apiResult = await HttpHelper<object>.DeleteAsync($"{ApiUrl.DeleteRuleMapping}/{Id}");
                if (apiResult.Code == StatusCodeEnum.OK)
                {
                    await MessageBox.ShowAsync("删除成功");
                    OnDeleteCompleted();
                }
                else
                {
                    await MessageBox.ShowAsync($"删除失败: {apiResult.Msg}");
                }
            });
        }

        /// <summary>
        /// 重置表单
        /// </summary>
        protected override void ResetForm()
        {
            Key = null;
            Val = null;
            RegStr = null;
            Description = null;
            SelectedTypeIndex = 0;
            MappingDetailsList.Clear();
        }

        #endregion

        #region 映射详情操作方法

        /// <summary>
        /// 添加映射详情
        /// </summary>
        public async Task AddMappingDetailsAsync()
        {
            try
            {
                // 根据选中的类型打开相应的选择对话框
                var selectedType = (MappingDetailsDisplayType)SelectedTypeIndex;
                switch (selectedType)
                {
                    case MappingDetailsDisplayType.Value:
                        // 打开值选择对话框
                        break;
                    case MappingDetailsDisplayType.Brand:
                        await SelectBrandAsync();
                        break;
                    case MappingDetailsDisplayType.VehicleSeries:
                        await SelectVehicleSeriesAsync();
                        break;
                    case MappingDetailsDisplayType.CarTypeVersion:
                        await SelectCarTypeVersionAsync();
                        break;
                    case MappingDetailsDisplayType.CarParts:
                        await SelectCarPartsAsync();
                        break;
                }
            }
            catch (Exception ex)
            {
                await MessageBox.ShowAsync($"添加映射详情失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 删除选中的映射详情
        /// </summary>
        public void RemoveSelectedMappingDetails()
        {
            var selectedItems = MappingDetailsList.Where(x => x.IsSelected).ToList();
            foreach (var item in selectedItems)
            {
                MappingDetailsList.Remove(item);
            }
        }

        /// <summary>
        /// 选择品牌
        /// </summary>
        private async Task SelectBrandAsync()
        {
            try
            {
                var dialog = new Page_Brand_Query();
                var viewModel = dialog.DataContext as BrandQueryViewModel;
                if (viewModel != null)
                {
                    viewModel.InformationRequested += (sender, brand) =>
                    {
                        if (brand != null)
                        {
                            MappingDetailsList.Add(new MappingDetails
                            {
                                Id = brand.Id,
                                Key = brand.Name,
                                Value = brand.Name
                            });
                        }
                    };
                }
                await dialog.ShowDialogAsync(Owner);
            }
            catch (Exception ex)
            {
                await MessageBox.ShowAsync($"选择品牌失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 选择车系
        /// </summary>
        private async Task SelectVehicleSeriesAsync()
        {
            try
            {
                var dialog = new Page_VehicleSeries_Query();
                var viewModel = dialog.DataContext as VehicleSeriesQueryViewModel;
                if (viewModel != null)
                {
                    viewModel.InformationRequested += (sender, series) =>
                    {
                        if (series != null)
                        {
                            MappingDetailsList.Add(new MappingDetails
                            {
                                Id = series.Id,
                                Key = series.Name,
                                Value = series.Name
                            });
                        }
                    };
                }
                await dialog.ShowDialog();
            }
            catch (Exception ex)
            {
                await MessageBox.ShowAsync($"选择车系失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 选择车型版本
        /// </summary>
        private async Task SelectCarTypeVersionAsync()
        {
            try
            {
                var dialog = new Page_CarTypeVersion_Query();
                var viewModel = dialog.DataContext as CarTypeVersionQueryViewModel;
                if (viewModel != null)
                {
                    viewModel.InformationRequested += (sender, version) =>
                    {
                        if (version != null)
                        {
                            MappingDetailsList.Add(new MappingDetails
                            {
                                Id = version.Id,
                                Key = version.Name,
                                Value = version.Name
                            });
                        }
                    };
                }
                await dialog.ShowDialog();
            }
            catch (Exception ex)
            {
                await MessageBox.ShowAsync($"选择车型版本失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 选择汽车配件
        /// </summary>
        private async Task SelectCarPartsAsync()
        {
            try
            {
                var dialog = new AvalonAdmin.Pages.CarType.Views.CarParts.Page_CarParts_Query();
                var viewModel = dialog.DataContext as AvalonAdmin.Pages.CarType.ViewModels.CarParts.CarPartsQueryViewModel;
                if (viewModel != null)
                {
                    viewModel.InformationRequested += (sender, args) =>
                    {
                        if (args.SelectedModel is List<RepCarParts> carPartsList && carPartsList.Any())
                        {
                            var parts = carPartsList.First();
                            MappingDetailsList.Add(new MappingDetails
                            {
                                Id = parts.Id,
                                Key = parts.Name,
                                Value = parts.Name
                            });
                        }
                    };
                }
                await dialog.ShowDialog();
            }
            catch (Exception ex)
            {
                await MessageBox.ShowAsync($"选择汽车配件失败：{ex.Message}");
            }
        }

        #endregion

        #region 验证方法

        /// <summary>
        /// 验证输入
        /// </summary>
        protected bool ValidateInput()
        {
            if ((!string.IsNullOrWhiteSpace(Val) || !string.IsNullOrWhiteSpace(Key))
                && !string.IsNullOrWhiteSpace(RegStr))
            {
                MessageBox.ShowAsync("正则匹配不能和值匹配同时使用！");
                return false;
            }

            if (!string.IsNullOrWhiteSpace(Val) && string.IsNullOrWhiteSpace(Key)
                || string.IsNullOrWhiteSpace(Val) && !string.IsNullOrWhiteSpace(Key))
            {
                MessageBox.ShowAsync("匹配键和匹配值不能为空！");
                return false;
            }

            if (SelectedTypeIndex == -1)
            {
                MessageBox.ShowAsync("类型必须选择");
                return false;
            }

            if (MappingDetailsList.Count == 0)
            {
                MessageBox.ShowAsync("详情列表必须选择值！");
                return false;
            }

            return base.ValidateInput();
        }

        #endregion

        #region 嵌套类型定义

        /// <summary>
        /// 映射详情显示类型枚举
        /// </summary>
        public enum MappingDetailsDisplayType
        {
            Value,
            Brand,
            VehicleSeries,
            CarTypeVersion,
            CarParts
        }

        /// <summary>
        /// 映射详情模型
        /// </summary>
        public class MappingDetails
        {
            public string? Id { get; set; }
            public string? Key { get; set; }
            public string? Value { get; set; }
            public bool IsSelected { get; set; }
        }

        #endregion

        #region 事件处理方法

        /// <summary>
        /// 品牌
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Brand_InformationRequested(object sender, InformationEventArgs<RepBrand> e)
        {
            if (e.Information != null)
            {
                MappingDetailsList = new ObservableCollection<MappingDetails>();
                MappingDetails details = new MappingDetails();
                details.Key = "品牌";
                details.Value = e.Information.Name;
                details.Id = e.Information.Id;
                MappingDetailsList.Add(details);
            }
        }

        /// <summary>
        /// ��ϵ
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void VehicleSeries_InformationRequested(object sender, InformationEventArgs<RepVehicleSeries> e)
        {
            if (e.Information != null)
            {
                MappingDetailsList = new ObservableCollection<MappingDetails>();
                MappingDetails details = new MappingDetails();
                details.Key = "车系";
                details.Value = e.Information.Name;
                details.Id = e.Information.Id;
                MappingDetailsList.Add(details);
            }
        }

        /// <summary>
        /// ����
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CarType_InformationRequested(object sender, InformationEventArgs<RepCarType> e)
        {
            if (e.Information != null)
            {
                MappingDetailsList = new ObservableCollection<MappingDetails>();
                MappingDetails details = new MappingDetails();
                details.Key = "车型";
                details.Value = e.Information.Name;
                details.Id = e.Information.Id;
                MappingDetailsList.Add(details);
            }
        }

        /// <summary>
        /// ���Ͱ汾
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CarTypeVersion_InformationRequested(object sender, InformationEventArgs<RepCarTypeVersion> e)
        {
            if (e.Information != null)
            {
                MappingDetailsList = new ObservableCollection<MappingDetails>();
                MappingDetails details = new MappingDetails();
                details.Key = "车型版本";
                details.Value = e.Information.SalesName;
                details.Id = e.Information.Id;
                MappingDetailsList.Add(details);
            }
        }

        /// <summary>
        /// ���
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CarParts_InformationRequested(object sender, ListInformationEventArgs<RepCarParts> e)
        {
            if (e.Information != null)
            {
                RepCarParts repCarParts = e.Information.FirstOrDefault();
                MappingDetailsList = new ObservableCollection<MappingDetails>();
                MappingDetails details = new MappingDetails();
                details.Key = "配件";
                details.Value = repCarParts.Name;
                details.Id = repCarParts.Id;
                MappingDetailsList.Add(details);
            }
        }

        #endregion

        #region SimpleIntegratedViewModel 抽象方法实现
        /// <summary>
        /// 异步查询数据
        /// </summary>
        /// <returns></returns>
        public override async Task<bool> QueryAsync()
        {
            await MessageBox.ShowAsync("待实现");
            return true;
        }

        /// <summary>
        /// 重置表单
        /// </summary>
        protected override void Reset()
        {
            // 待实现
        }

        /// <summary>
        /// 提交数据
        /// </summary>
        /// <returns></returns>
        protected override async Task SubmitAsync()
        {
            await SaveAsync();
        }

        /// <summary>
        /// 异步添加数据
        /// </summary>
        /// <param name="obj">要添加的对象</param>
        /// <returns></returns>
        public async Task AddAsync(RepRuleMapping? obj = default)
        {
            await MessageBox.ShowAsync("待实现");
        }

        /// <summary>
        /// 异步更新数据
        /// </summary>
        /// <param name="obj">要更新的对象</param>
        /// <returns></returns>
        public async Task UpdateAsync(RepRuleMapping? obj = default)
        {
            await MessageBox.ShowAsync("待实现");
        }

        /// <summary>
        /// 异步删除数据
        /// </summary>
        /// <param name="obj">要删除的对象</param>
        /// <returns></returns>
        public async Task DeleteAsync(RepRuleMapping? obj = default)
        {
            await MessageBox.ShowAsync("待实现");
        }

        /// <summary>
        /// 异步批量删除数据
        /// </summary>
        /// <param name="items">要删除的项目集合</param>
        /// <returns></returns>
        public async Task BatchDeleteAsync(IEnumerable<RepRuleMapping>? items = null)
        {
            await MessageBox.ShowAsync("待实现");
        }

        /// <summary>
        /// 获取项目的选中状态
        /// </summary>
        /// <param name="item">项目</param>
        /// <returns>是否选中</returns>
        protected bool GetIsSelected(RepRuleMapping item)
        {
            return item?.IsSelected ?? false;
        }

        /// <summary>
        /// 设置项目的选中状态
        /// </summary>
        /// <param name="item">项目</param>
        /// <param name="isSelected">是否选中</param>
        protected void SetIsSelected(RepRuleMapping item, bool isSelected)
        {
            if (item != null)
            {
                item.IsSelected = isSelected;
            }
        }
        #endregion

        #region 重写方法
        // 注意：BaseModifyViewModel 不包含 OnSelectedModelChanged 和 OnDataChanged 方法
        // 如果需要这些功能，应该考虑继承其他基类或实现相应的事件处理
        #endregion
    }
}



